package top.yueyazhui.vhr.controller.common;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.csource.common.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.yueyazhui.vhr.bean.Response;
import top.yueyazhui.vhr.model.File;
import top.yueyazhui.vhr.service.FileService;
import top.yueyazhui.vhr.util.FastDFSUtil;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/common/file")
@Api(tags = "/** 公共_文件 **/")
public class FileController {

    @Autowired
    FileService fileService;
    @Autowired
    FastDFSUtil fastDFSUtil;

    @PostMapping("/upload")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @ApiImplicitParam(name = "remark", value = "备注", required = false)
    public Response upload(@RequestParam() MultipartFile file, String remark) throws IOException, MyException {
        if (file.isEmpty()) {
            return Response.error("文件为空，上传失败！");
        }

        String fileName = file.getOriginalFilename();
        Long size = file.getSize();
        String type = file.getContentType();
        byte[] bytes = file.getBytes();
        Integer index = fileName.lastIndexOf('.');
        String suffix = fileName.substring(index + 1, fileName.length());
        String url = fastDFSUtil.upload(bytes, suffix);

        File file1 = new File();
        file1.setUploadTime(new Date());
        file1.setName(fileName);
        file1.setSize(size);
        file1.setType(type);
        file1.setSuffix(suffix);
        file1.setUrl(url);
        file1.setRemark(remark);

        Integer result = fileService.insert(file1);
        if (result != 0) {
            file1.setId(result);
            return Response.success("上传成功！", file1);
        }
        return Response.error("上传失败！");
    }

    @GetMapping("/download")
    @ApiOperation(value = "下载文件", notes = "下载文件")
    public ResponseEntity<byte[]> download(String url) throws MyException, IOException {
        File file = fileService.getByUrl(url);
        byte[] bytes = fastDFSUtil.download(url);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
    }
}
